<?php

namespace App\Supports\Payment\Methods\Wxpay;

use Carbon\Carbon;
use App\Models\GoldRecord;
use App\Models\User;
use App\Models\GoldCharge;
use App\Events\OrderPaidEvent;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodCallback;
use Illuminate\Support\Facades\Redis;
use App\Jobs\PayCacheOrderJob;
use Rainsens\Dinglog\Facades\Dinglog;
use App\Events\GoldRecordPaidEvent;

class CallbackPayStorm extends Method implements MethodCallback
{
	protected function isPaidSuccess($data)
	{
		$wxpayStatus = isset($data['return_code']) ? $data['return_code'] : '';
		if ($wxpayStatus === 'SUCCESS') {
			return true;
		}
		return false;
	}

	public function markAsPaid($order = null, $data = null)
	{
		$GoldRecord->update([
			'paid_at' => Carbon::now(),
			'paid_method' => 'wxpay',
			'paid_number' => $data['transaction_id'],
		]);

		return 'success';
	}

	public function callback($data = null)
	{
		Dinglog::text(json_encode($data));
		if (! $this->isPaidSuccess($data)) {
			return 'fail';
		}

		$number = $data['out_trade_no'];
		Dinglog::text($number);

		if ($charge = GoldCharge::where('number', $number)->whereNotNull("paid_at")->first()) {
				Dinglog::text("success:".$number);
				return 'success';
		}


		$cacheIds = Redis::zRange($number, 0, -1);
		$priceTotal = 0;
		$updateUid = 0;

		foreach($cacheIds as $cid) {
			Dinglog::text($cid);
			$price = Redis::hGet($cid,'record_all_price');
			$uid = Redis::hGet($cid,'user_id');
			$user = User::find($uid);
			$updateUid = $uid;
			$user->addRecordToPendingCache($cid);
			$user->delRecordFromUnpaidCache($cid);

			Dinglog::text("订单ID：".$cid);
			$record = GoldRecord::query()->where(['cache_id'=> $cid])->first();
			$record->update(['paid_at' => Carbon::now(), 'paid_method' => 'wxpay']);

			event(new GoldRecordPaidEvent($record));

			$record->unsetRelations();
			
			$priceTotal = $price + $priceTotal;

		}


		$charge = GoldCharge::create([
			'paid_at' => Carbon::now(),
			'paid_method' => 'wxpay',
			'paid_number' => $data['transaction_id'],
			'total_amount' => $priceTotal,
			'user_id' => $updateUid,
			'number' => $number
		]);



		/* $this->markAsPaid($data,$priceTotal);*/

		//return 'success';
			
		/*if (!$order = Order::where('number', $number)->get()) {
			return 'fail';
		}

		if ($order->isPaid()) {
			return 'success';
		}*/

		//return $this->markAsPaid($order, $data);
	}
}
